package string

import (
	"bufio"
	"fmt"
	"os"
	"regexp"
)

// "Hello{ACD}Wor{D}ld" -> "HelloWorld"
// "{..}" -> ""
func replace(src string) string {
	return replaceHelper(src, "")
}

func replaceHelper(src, des string) string {
	reg := regexp.MustCompile(`{\w*}`)
	return reg.ReplaceAllString(src, des)
}

// Searches for (regular) expressions in text files
// Every single line is read and if the line matches the pattern provided on the command line,
// that line is printed
func grep(re, filename string) {
	regex, err := regexp.Compile(re)
	if err != nil {
		panic("The regular expressions is wrong in syntax")
	}

	fh, err := os.Open(filename)
	if err != nil {
		panic("Failed to open file: " + filename)
	}
	defer fh.Close()

	f := bufio.NewReader(fh)
	var buf []byte
	for {
		buf, _, err = f.ReadLine()
		if err != nil {
			return
		}

		s := string(buf)
		if regex.MatchString(s) {
			fmt.Println(s)
		}
	}
}
